package com.ocean.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * https://leetcode.cn/problems/binary-tree-postorder-traversal/
 * <p>
 * 后序遍历：左-右-根
 */
public class BinaryTreePostorderTraversal {


    public static void main(String[] args) {
        BinaryTreePostorderTraversal traversal = new BinaryTreePostorderTraversal();
        List<Integer> res = traversal.postorderTraversal2(TreeNode.getRoot());
        System.out.println(res);
    }


    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        postorder(root, res);
        return res;
    }


    private void postorder(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        postorder(root.getLeft(), res);
        postorder(root.getRight(), res);
        res.add(root.getValue());
    }


    public List<Integer> postorderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode prev = null;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.getLeft();
            }
            root = stack.pop();
            // root.getRight=pre 记录右边已经走过了 当前中间节点直接添加结果
            if (root.getRight() == null || root.getRight() == prev) {
                res.add(root.getValue());
                prev = root;
                root = null;
            } else {
                stack.push(root);
                root = root.getRight();
            }
        }
        return res;
    }
}
